package main

import (
	"encoding/csv"
	"log"
	"os"

	"github.com/antandros/go-dpkg"
)

func main() {
	// 获取已安装的包列表
	packages, err := dpkg.GetPackages()
	if err != nil {
		log.Fatalf("Failed to get installed packages: %v", err)
	}

	// 创建或截断 installed.csv 文件
	file, err := os.Create("installed.csv")
	if err != nil {
		log.Fatalf("Failed to create CSV file: %v", err)
	}
	defer file.Close()

	// 创建 CSV writer
	writer := csv.NewWriter(file)
	defer writer.Flush()

	// 写入 CSV 头部
	if err := writer.Write([]string{"name", "version", "installed"}); err != nil {
		log.Fatalf("Failed to write CSV header: %v", err)
	}

	// 遍历所有包并写入 CSV
	for _, pkg := range packages {
		record := []string{
			pkg.PackageName,
			pkg.Version,
			pkg.Installed,
		}
		if err := writer.Write(record); err != nil {
			log.Printf("Failed to write record for package %s: %v", pkg.PackageName, err)
			continue
		}
	}

	log.Println("Successfully generated installed.csv")
}
